package com.ty.service.impl;

import com.ty.bean.Menu;
import com.ty.bean.Role;
import com.ty.bean.Users;
import com.ty.dao.RoleDao;
import com.ty.dao.UsersDao;
import com.ty.dao.impl.RoleDaoImpl;
import com.ty.dao.impl.UsersDaoImpl;
import com.ty.service.UsersService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 田野
 */
public class UsersServiceImpl implements UsersService {

    private UsersDao usersDao = new UsersDaoImpl();
    private RoleDao roleDao = new RoleDaoImpl();

    @Override
    public Users login(String username, String password) {
        Users users = usersDao.login(username, password);
        if (users == null){
            return null;
        }

        // 根据角色id，查询角色信息和菜单信息（三表联查）
        Integer roleId = users.getRoleId();
        Role role = roleDao.findById(roleId);
        // 需要对菜单进行分级
        List<Menu> menuList = role.getMenuList();

        // 保存分级以后的菜单
        List<Menu> newMenu = new ArrayList<>();
        for (Menu menu : menuList) {
            // 一级菜单
            if (menu.getUpMenuId()==0){

                List<Menu> secondList = new ArrayList<>();
                for (Menu second : menuList) {
                    // 二级菜单
                    if (second.getUpMenuId().equals(menu.getMenuId())){
                        secondList.add(second);
                    }
                }
                menu.setSecondMenuList(secondList);
                newMenu.add(menu);
            }

        }
        // 用户包含角色，角色包含菜单，这些菜单是分级菜单
        role.setMenuList(newMenu);
        users.setRole(role);

        return users;
    }

    @Override
    public List<Users> getUsersList(int pageIndex, int pageSize) {
        return usersDao.getUsersList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return usersDao.total();
    }

    @Override
    public List<Role> getRoleList() {
        return usersDao.getRoleList();
    }

    @Override
    public int insertUser(Users users) {
        return usersDao.insertUser(users);
    }
}
